angular.module('HTRD_AutoConsole.A').controller('ManagerControlListCtrl', ['$scope', '$state', '$window', '$timeout', 'ManagerControlServ', 'ManagerHolidayServ', 'ManagerListServ', 'AlertServ', 'DialogServ',
    function ($scope, $state, $window, $timeout, ManagerControlServ, ManagerHolidayServ, ManagerListServ, AlertServ, DialogServ) {
        var starpAside, starpModal;

        //选择流程
        var activeProcess = function (item) {
          console.log('activeProcess', item)
          $scope.controlModel.pipeline = item.id;
          $scope.controlModel.pipelineName = item.name;
        };

        var getProcessListByName = function (item) {
          ManagerListServ.getProcessList({
            search: item
          })
          .then(function (ret) {

            if (ret.status === 200) {
              $scope.$broadcast('changeSelectFilterList', {
                data: ret.results.data,
                id: 'controlInfoSelectId'
              });
            };
          });
        };

        var getProcessListByName1 = function (item) {
          $scope.searchControlListText = item;
          ManagerListServ.getProcessList({
              search: item
          })
          .then(function (ret) {

            if (ret.status === 200) {
              $scope.$broadcast('changeSelectFilterList', {
                  data: ret.results.data,
                  id: 'controlListSelectId'
              });
            };
          });
        };

        var switchActive = function (item) {
          $scope.controlModel.isOpen = item;
        };

        // 拼接配置结果文字

        var joinConfigText = function (data) {
            $scope.data = data;

            if ($scope.data['dateMin'] && $scope.data['dateHour'] && $scope.data['dayAndMonth'] && $scope.data['dayAndWeek'] && $scope.data['month']) {
                var nextMin = $scope.data.dateMin.text;
                var nextHour = $scope.data['dateHour']['text'];
                var nextDay = $scope.data['dayAndMonth']['text'];
                var nextWeek = $scope.data['dayAndWeek']['text'];
                var nextMonth = $scope.data['month']['text'];

                var reg = /^[\*]/;
                var newReg = /[\/]/;
                //var work = $scope.data.isExec? ($scope.controlModel.holidayYear?$scope.controlModel.holidayYear: '2017年') + '年执行时间' : ' ';
                var work = $scope.data.isExec? ($scope.controlModel.holidayYear?$scope.controlModel.holidayYear+'年': '  '): ' ';

                 var showWorkTime = '';
                 if ($scope.data.execCycleMap[1] && $scope.data.execCycleMap[2] ) {
                     showWorkTime = ' 全年 ';
                 } else if ($scope.data.execCycleMap[1]){
                     showWorkTime=' 工作日 ';
                 } else if ($scope.data.execCycleMap[2]){
                     showWorkTime=' 节假日 ';
                 }

                if (reg.test(nextMin) || reg.test(nextHour) || reg.test(nextDay) || reg.test(nextWeek) || reg.test(nextMonth) || newReg.test(nextMin) || newReg.test(nextHour) || newReg.test(nextDay)  || newReg.test(nextWeek) || newReg.test(nextMonth)) {
                  var tempNextMin = nextMin.replace(reg, '每').replace(newReg, '分钟每');
                  var tempNextHour = nextHour.replace(reg, '每').replace(newReg, '小时每');
                  var tempNextDay = nextDay.replace(reg, '每').replace(newReg, '日每');

                  var tempNextWeek = nextWeek.replace(reg, '').replace(newReg, '每');

                  var tempNextMonth = nextMonth.replace(reg, '每').replace(newReg, '月每');

                  // 例如：1-5 / 2  表示：1 - 5月每2个月1-5日每2天和周一 - 周五每2天1：00-5：00每2小时01-05分钟每2分钟
                  var tempNameTime= ($scope.data.isExec?'允许触发执行时间: ': '禁止触发执行时间: ') + ($scope.data.holidayName === '请选择'?' ': $scope.data.holidayName);
                  var temp = tempNextMonth + '月' + tempNextDay + '日'  + '和每周' + tempNextWeek + '的' + tempNextHour + '时' + tempNextMin + '分钟';
                  var tempDelWeek = tempNextMonth + '月' + tempNextDay + '日' + tempNextHour + '时' + tempNextMin + '分钟';

                  $scope.controlModel.text= tempNameTime + showWorkTime  +work+temp;

                  if (nextMin === '*' && nextHour === '*' && nextDay === '*' && nextWeek === '*' && nextMonth === '*'){  //全是 * 的规则
                      $scope.controlModel.text=tempNameTime + showWorkTime + '每分钟'

                  } else if (nextWeek === '*' && nextMonth === '*' && nextHour === '*' && nextDay === '*'){
                      $scope.controlModel.text = tempNameTime+ showWorkTime  + '每小时' +tempNextMin + '分'
                  } else if (nextWeek === '*' && nextMonth === '*' && nextDay === '*'){
                      $scope.controlModel.text = tempNameTime + showWorkTime  + '每天' +tempNextHour + '时' +tempNextMin + '分钟'
                  } else if (nextWeek === '*'){
                      $scope.controlModel.text=tempNameTime+ showWorkTime +tempDelWeek;
                  }
                } else {
                    var tempNameTimeShow= ($scope.data.isExec?'允许触发执行时间: ': '禁止触发执行时间: ');
                    var nextWeekStr = '周';
                    var nextWeekStrMap = {
                      1: '周一',
                      2: '周二',
                      3: '周三',
                      4: '周四',
                      5: '周五',
                      6: '周六',
                      7: '周日'
                    };

                    if (nextWeekStrMap[nextWeek]) {
                      nextWeekStr = nextWeekStrMap[nextWeek];
                    }
                    else if (nextWeek.length === 3) {
                      var nextWeekList = [];
                      var splitType;

                      if (nextWeek.indexOf('-') !== -1) {
                        splitType = '-';
                      }

                      else if (nextWeek.indexOf(',') !== -1) {
                        splitType = ',';
                      }

                      else if (nextWeek.indexOf('-') !== -1) {
                        splitType = '-';
                      }

                      else if (nextWeek.indexOf('，') !== -1) {
                        splitType = '，';
                      };
                      nextWeekList = nextWeek.split(splitType);
                      var nextWeekStrList = nextWeekList.map(function(item) {

                        if (!!nextWeekStrMap[item]) {
                          return nextWeekStrMap[item]
                        };
                      })

                      if (nextWeekStrList.length === 2) {
                        nextWeekStr = nextWeekStrList.join(splitType);
                        // nextWeekStr = [nextWeekStrMap[nextWeekList[0]] , nextWeekStrMap[nextWeekList[1]]].join(splitType);
                      };
                    }

                    console.log('nextWeek', nextWeek);
                    console.log('nextWeekStr', nextWeekStr);
                    var temp = nextMonth + '月' + nextDay + '日' + '和每' + nextWeekStr + nextHour + '时' + nextMin + '分钟';
                    console.log('temp', temp);
                    $scope.controlModel.text = tempNameTimeShow + showWorkTime + work + temp;
                }

            }
        };


        // 选择执行设置
        var toggleExecSetting = function (isExec) {
            $scope.controlModel.isExec = isExec;
        };

        var checkedExecCycle = function (item) {
          $scope.controlModel.execCycleMap = $scope.controlModel.execCycleMap || {};
          $scope.controlModel.execCycleMap[item] = !!!$scope.controlModel.execCycleMap[item];
        };

        var addControlProject = function () {
          $scope.controlModel = {
            name: '',
            isOpen: true,
            isExec: true,
            holidayId: 1,
            holidayName: '',
            execCycleMap: {
                '1': true,
                '2': false
            },
            dateMin: {
                text: '*',
                state: false
            },
            dateHour: {
                text: '*',
                state: false
            },
            dayAndMonth: {
                text: '*',
                state: false
            },
            month: {
                text: '*',
                state: false
            },
            dayAndWeek: {
                text: '*',
                state: false
            }
          };

          starpAside = DialogServ.aside({
              'scope': $scope,
              'backdrop': 'static',
              'title': '创建流程计划',
              'templateUrl': 'view/console/aside/controlAdd.html'
          });

          $timeout(function () {
              $('.aside-body').height($('.aside').height() - 150);
          }, 100);

          $scope.getHolidayList();
        };

        var editControlProject = function (item) {
            $scope.controlId = item.id;
            ManagerControlServ.getManagerControlInfo({
                    id: item.id
                })
                .then(function(ret) {

                    if (ret.status === 200) {
                        var data = ret.results;
                        var execCycleArray = data.exec_type.split(',');
                        var holidayName = '';
                        var holidayYear;

                        $scope.holidayList.map(function(holidayItem) {

                            if (data.holiday === holidayItem.id) {
                                holidayName = holidayItem.name;
                                holidayYear = holidayItem.year;
                            };
                        });

                        $scope.controlModel = {
                            name: data.name ,
                            isOpen: data.status,
                            isExec: data.type,

                            holidayId: data.holiday,
                            holidayName: holidayName || '请选择',
                            holidayYear: holidayYear,

                            pipeline: data.pipeline,
                            pipelineName: data.pipeline_name,

                            execCycleMap: {
                                1: (execCycleArray.indexOf('1') !== -1),
                                2: (execCycleArray.indexOf('2') !== -1)
                            },

                            dateMin: {
                                text: data.minute || '*',
                                state: false
                            },

                            dateHour: {
                                text: data.hour || '*',
                                state: false
                            },

                            dayAndMonth: {
                                text: data.day_of_month || '*',
                                state: false
                            },

                            month: {
                                text: data.month_of_year || '*',
                                state: false
                            },

                            dayAndWeek: {
                                text: data.day_of_week || '*',
                                state: false
                            },

                            text: data.result_info
                        };

                        starpAside = DialogServ.aside({
                            'scope': $scope,
                            'backdrop': 'static',
                            'title': '编辑流程计划',
                            'templateUrl': 'view/console/aside/controlAdd.html'
                        });

                        $timeout(function () {
                            $('.aside-body').height($('.aside').height() - 150);
                        }, 100);
                    }
                    else {
                        console.log('error');
                    }
                });
        };

        var submitAddOrEditControlProject = function () {
          var execTypeList = [];

          for (var key in $scope.controlModel.execCycleMap) {

            if (!!$scope.controlModel.execCycleMap[key]) {
              execTypeList.push(key);
            };
          };

          var param = {
            id: $scope.controlId || null,
            name: $scope.controlModel.name,
            type: $scope.controlModel.isExec,
            status: $scope.controlModel.isOpen,
            exec_type: execTypeList.join(','),

            minute: $scope.controlModel.dateMin.text || '*',
            hour: $scope.controlModel.dateHour.text || '*',
            day_of_week: $scope.controlModel.dayAndWeek.text || '*',
            day_of_month: $scope.controlModel.dayAndMonth.text || '*',
            month_of_year: $scope.controlModel.month.text || '*',
            result_info: $scope.controlModel.text || '',

            holiday: $scope.controlModel.holidayId,
            pipeline: $scope.controlModel.pipeline
          };

          if (!$scope.controlId) {
            if(param.name&&param.pipeline){
                ManagerControlServ.addManagerControlInfo(param)
                    .then(function (ret) {

                        $scope.ret = ret.results;
                        AlertServ.showSuccess('保存成功');
                        $scope.getControlProjectList();
                        starpAside.hide();
                    });
            }else{
                // 不填 弹框
                starpModal = DialogServ.modal({
                    'scope': $scope,
                    'backdrop': 'static',
                    'title': '删除流程计划',
                    'templateUrl': 'view/console/modal/controlListEmpty.html'
                });
                //alert("计划名称 和 选择流程 为必填项!")
            }


          } else {
            ManagerControlServ.editManagerControlInfo(param)
            .then(function (ret) {
              AlertServ.showSuccess('编辑成功');
              $scope.getControlProjectList();
              starpAside.hide();
            })
          }
        };

        var delControlProject = function (item) {
            $scope.controlId = item.id;
            $scope.controlContent = item.title;
            starpModal = DialogServ.modal({
                'scope': $scope,
                'backdrop': 'static',
                'title': '删除流程计划',
                'templateUrl': 'view/console/modal/controlConfirmDelete.html'
            });
        };

        var submitDelControlProject = function () {
            starpModal.hide();
            AlertServ.showSuccess('删除成功');

        };

        var closeControlProjectInfo = function () {
            $scope.controlModel = {};
            starpAside.hide();
        };

        var changeHoliday = function (item) {
            $scope.item = item;
            $scope.controlModel.holidayId = item.id;
            $scope.controlModel.holidayName = item.name;
            $scope.controlModel.holidayYear = item.year;
        };

        var getHolidayList = function () {
          var arg = {
              page: 'false'
          };
          ManagerHolidayServ.getHolidayList(arg)   // ，获取全部数据接口
          .then(function (ret) {

            if (ret.status === 200) {
              $scope.holidayList = ret.results;
            } else {
              $scope.holidayList = [];
            };
          });
        };

        var getControlProjectList = function () {   //首次获取数据,并刷新
            ManagerControlServ.getManagerControlList($scope.pageConfig)
                .then(function (ret) {
                    if (ret.status === 200) {
                        $scope.flowDispathList = ret.results.data;
                        $scope.controlList = $scope.flowDispathList;
                        $scope.pageConfig.page = ret.results.page;
                        $scope.$broadcast('toList', {
                            page: $scope.pageConfig.page,
                            count: ret.results.count
                        });

                    } else {
                        $scope.flowDispathList = [];
                    }
                });

        };

        var getControlInfo = function (data) {
            $scope.controlList.map(function (item) {
                //$scope.newControlList.map(function (item) {
                item.active = false;
            });
            $scope.activeId = data.id;
            data.active = true;
        };


        //搜索功能
        var search = function() {
            $scope.pageConfig.page = 1;
            $scope.searchQuery = $scope.query;

            //$scope.getControlProjectList();
            $scope.getProcessList();
        };

        var getProcessList = function() {
          var params = {
            page: $scope.pageConfig.page
          };

          if (!!$scope.searchControlListText) {
            params.pipeline = $scope.controlModel.pipeline;
          };

          ManagerControlServ.getManagerControlList(params)
          .then(function(res) {

            if (res.status === 200) {
                $scope.controlList = res.results.data;
                $scope.pageConfig.page = res.results.page;
                $scope.$broadcast('toList', {
                    page: $scope.pageConfig.page,
                    count: res.results.count
                });
            } else{
                $scope.controlList=[];
            }
          });
        };




        //==========获取手动添加数据
        var getConfigStr = function () {
            $scope.newProjectName = $scope.controlModel.name;
        };


        var bindListener = function () {
            //弹框
           // $scope.changeDateCycle=changeDateCycle;
           // $scope.canceleMode=canceleMode;

            //搜索功能<-
            $scope.search = search;
            $scope.getProcessList = getProcessList;
            //搜索功能 ->

            $scope.switchActive = switchActive;
            $scope.toggleExecSetting = toggleExecSetting;
            $scope.checkedExecCycle = checkedExecCycle;
            $scope.addControlProject = addControlProject;
            $scope.delControlProject = delControlProject;
            $scope.getControlProjectList = getControlProjectList;
            $scope.getControlInfo = getControlInfo;
            $scope.changeHoliday = changeHoliday;
            $scope.submitAddOrEditControlProject = submitAddOrEditControlProject;
            $scope.editControlProject = editControlProject;
            $scope.getHolidayList = getHolidayList;
            $scope.joinConfigText = joinConfigText;
            $scope.closeControlProjectInfo = closeControlProjectInfo;
            $scope.submitDelControlProject = submitDelControlProject;
            $scope.getProcessListByName = getProcessListByName;
            $scope.getProcessListByName1 = getProcessListByName1;

            $scope.activeProcess = activeProcess;
            //======
            $scope.getConfigStr = getConfigStr;
            // $scope.changeText=changeText;
        };

        var initPlugins = function () {
            //搜索功能
            $scope.pageConfig = {
                page: 1
            };


            // 创建流程计划表单数据
            $scope.controlModel = {};

            // 面包屑
            $scope.crumbsConfig = {
                index: {
                    title: '流程调度',
                    icon: 'htrd-icon-control-sm'
                }
            };

            $scope.helpTextMap = {
                'dateMin': {
                    title: '分钟',
                    data: [
                        {
                            title: '0 - 59',
                            text: '允许值是0到59之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如: *表示每分钟'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：0,30表示0和30分钟'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：0-5表示0,1,2,3,4,5分钟'
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如: 0-30/2表示0-30分钟之间每2分钟'
                        }
                    ]
                },

                'dateHour': {
                    title: '小时',
                    data: [
                        {
                            title: '0 - 23',
                            text: '允许值是0到23之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如: *表示每小时'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：0,12表示0和12小时'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：19-23表示19,20,21,22,23小时 '
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：0-20/2表示0-20小时之间每2小时'
                        }
                    ]
                },

                'dayAndMonth': {
                    title: '日',
                    data: [
                        {
                            title: '0 - 31',
                            text: '允许值是1到31之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如：*表示本月每一天'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：1,15表示本月1日和15日'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：1-5表示本月1,2,3,4,5日'
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：1-20/2表示1-20日之间每2天 '
                        }
                    ]
                },

                'month': {
                    title: '月',
                    data: [
                        {
                            title: '0 - 12',
                            text: '允许值是1到12之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如：*表示每月'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：1,6表示1月和6月'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：1-3表示1月,2月,3月'
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：1-5/2表示周一-周五之间每2天'
                        }
                    ]
                },

                'dayToWeek': {
                    title: '周',
                    data: [
                        {
                            title: '0 - 6',
                            text: '允许值是0到6之间的任何整数,0=周日'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。*表示一周中的每一天'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：1,5表示周一和周五'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：1-3表示周一,周二,周三 '
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：1-5/2表示周一-周五之间每2天 '
                        }
                    ]
                }
            };

            var height = $(document).height()-243;
            $('.htrd-control-list-unplanned').css('height',height);

            $scope.getControlProjectList();
            $scope.getHolidayList();

            // 监听表单元素变化
            $scope.$watch('controlModel', function (n, o) {
                $scope.joinConfigText(n);
            }, true);


            $scope.helpToggle = function (item) {
                $scope.controlModel[item] = $scope.controlModel[item] || {};
                $scope.controlModel[item].state = !!!$scope.controlModel[item].state;
            };

            // 点击 input 删除*
            $scope.delText=function(item){
                //console.log($event.target);
                //$event.target.value="";
                $scope.controlModel[item].text=" ";

            }

            // 移除输入框默认值   日期月份不能为0
            $scope.change = function (item) {
              var text=$scope.controlModel[item].text;
              var month=$scope.controlModel['month'].text;
              var dayAndWeek=$scope.controlModel['dayAndWeek'].text;
              var dayAndMonth=$scope.controlModel['dayAndMonth'].text;
              var dateHour=$scope.controlModel['dateHour'].text;
              var dateMin=$scope.controlModel['dateMin'].text;

              var reg = /[^\*\/\-\d\,\，]+/.test( text);
              if (reg){
                $scope.controlModel[item].text = '*'
              };
              if (text == '' || month == '0' || dayAndMonth == '0' || dateMin >=60 || dateMin < 0 || dateHour >=24 || dateHour < 0 || dayAndMonth > 31 || dayAndMonth < 0 || dayAndWeek > 6 || dayAndWeek < 0  || month > 12 || month < 0) {
                   $scope.controlModel[item].text = '*';
              };
              var maxNumReg=/[\/\-]+/.test( text);
              var indexKey=text.indexOf('-');
              var lastKey=text.indexOf('/');
              var prevNum=parseInt(text.slice(0,indexKey));
              var nextNum=parseInt(text.slice(indexKey+1));
              var lastNum=parseInt(text.slice(lastKey+1));
              if (month==text){
                  if (maxNumReg){
                      if ( prevNum>12||prevNum<0||nextNum>12||nextNum<0||lastNum>12||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dayAndWeek==text){
                  if (maxNumReg){
                      if ( prevNum>6||prevNum<0||nextNum>6||nextNum<0||lastNum>6||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dayAndMonth==text){
                  if (maxNumReg){
                      if ( prevNum>31||prevNum<0||nextNum>31||nextNum<0||lastNum>31||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dateHour==text){
                  if (maxNumReg){
                      if ( prevNum>=24||prevNum<0||nextNum>=24||nextNum<0||lastNum>=24||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dateMin==text){
                  if (maxNumReg){
                      if ( prevNum>=60||prevNum<0||nextNum>=60||nextNum<0||lastNum>=60||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }

              // *2* - / ，
              if(/\-$/.test(text) ){
                  $scope.controlModel[item].text = '*';
              }
              if(/^\//.test(text) || /\/$/.test(text) || /\/\//.test(text)){
                  $scope.controlModel[item].text = '*';
              }
              if(/^,/.test(text) || /,$/.test(text) || /,,/.test(text)){
                  $scope.controlModel[item].text = '*';
              }
              if(/^\*/.test(text) || /\*$/.test(text) || /\*\*/.test(text) || /\d\*\d/.test(text)){
                  $scope.controlModel[item].text = '*';
              }


            };

            $scope.controlListSelectId = 'controlListSelectId';
            $scope.controlInfoSelectId = 'controlInfoSelectId';

            $scope.pageConfig = {};

            $scope.$on('toPage', function (evt, data) {
                $scope.pageConfig.page = data.page;
                $scope.getControlProjectList();
            });

            $scope.$on('toDate',function(evt,data){
               // (data + 'data')
            });
        };

        var init = function () {
            bindListener();
            initPlugins();
        };

        init();
    }]);
